<!--  -->
<template>
  <div class>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- alert提示 -->
      <el-alert title="添加商品信息" type="info" center :closable="false" show-icon></el-alert>
      <!-- steps步骤条 -->
      <el-steps align-center :active="+activeStep" finish-status="success" class="mt15 stops">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单 -->
      <el-form ref="addGoodsForm" :model="addGoodsForm" :rules="rules" label-position="top">
        <!-- tab标签页 -->
        <el-tabs
          v-model="activeStep"
          tab-position="left"
          class="mt15"
          @tab-click="handleTabChange"
          :before-leave="beforeLeaveHock"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="categoryLists"
                :props="catProps"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in paramsVals" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="box in item.attr_vals" :label="box" :key="box.attr_id"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in AttrVals" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button @click="savaAddForm" type="primary" class="mt15">提交表单</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 查看图片dirlog -->
    <el-dialog title="提示" :visible.sync="ImgDialogVisible">
      <span>图片预览</span>
      <img :src="goodsAddImg" alt style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  name: 'AddGoodsList',
  components: {},
  data() {
    return {
      categoryLists: [],
      ImgDialogVisible: false,
      activeStep: '0',
      paramsVals: [],
      AttrVals: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      catProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      goodsAddImg: '',
      addGoodsForm: {
        goods_name: '',
        //分类数组
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //商品描述
        goods_introduce: '',
        //图片数组
        pics: [],
        //参数数组
        attrs: []
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    //获取分类数据
    this.getCategoryLists()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  methods: {
    async handleTabChange() {
      //获取商品参数
      if (this.activeStep == 1) {
        let { data: res } = await this.$http.get(
          `categories/${this.addGoodsForm.goods_cat[2]}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.paramsVals = res.data
      }
      // 获取静态属性
      if (this.activeStep == 2) {
        let { data: res } = await this.$http.get(
          `categories/${this.addGoodsForm.goods_cat[2]}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.AttrVals = res.data
      }
    },
    //获取级联选择器分类数据
    async getCategoryLists() {
      let { data: res } = await this.$http.get('categories')
      this.categoryLists = res.data
    },
    //离开前的钩子
    beforeLeaveHock(activeName, oldName) {
      if (oldName == 0 && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请输入分类参数')
        return false
      }
    },
    //点击文件上传图片预览的钩子
    handlePreview(res) {
      this.goodsAddImg = res.url
      this.ImgDialogVisible = true
      console.log(res.url)
    },
    //处理文件上传图片移出的钩子
    handleRemove(res) {
      let index = this.addGoodsForm.pics.findIndex(
        item => item.pic == res.response.data.tmp_path
      )
      this.addGoodsForm.pics.splice(index, 1)
    },
    //上传成功钩子
    handleSuccess(res) {
      this.addGoodsForm.pics.push({ pic: res.data.tmp_path })
    },
    savaAddForm() {
      this.$refs.addGoodsForm.validate(async valid => {
        if (!valid) return this.$message.error('信息不完整')
        let form = JSON.parse(JSON.stringify(this.addGoodsForm))
        form.goods_cat = form.goods_cat.join(',')
        this.paramsVals.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.AttrVals.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        let { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
      })
    }
  }
}
</script>
<style scoped>
.el-step__title {
  font-size: 14px !important;
}
</style>